//
//  ContentView.swift
//  Aria2Proxy
//
//  Created by 张宇飞 on 2024/11/4.
//

import SwiftData
import SwiftUI

struct ContentView: View {
    @Environment(\.modelContext) private var modelContext
    @State private var url = ""
    @State private var saveDir = ""
    @State private var msg = "m3u8dl协议的格式为: m3u8dl:/链接地址#目录名"

    var body: some View {
        VStack {
            HStack {
                TextField("输入下载链接地址", text: $url)
                TextField("文件夹名", text: $saveDir)
                    .frame(width: 150.0)
                Button {
                    self.add()
                } label: {
                    Image(systemName: "plus")
                        .frame(width: 40)
                }
                .buttonStyle(.borderedProminent)
            }
            Spacer()
                .frame(height: 20.0)
            Text(msg)
                .font(.title)
                .multilineTextAlignment(.center)
        }
        .padding()
        .onOpenURL { u in
            self.handleURL(u: u)
        }
    }

    private func handleURL(u: URL) {
        // 获取 url
        let path = u.absoluteString
        let httpUrl = String(path[path.index(path.startIndex, offsetBy: u.scheme!.count + 2)...])

        // 自动化截取出来保存路径
        self.saveDir = ""
        self.url = ""
        if let dir = u.fragment(percentEncoded: false) {
            self.saveDir = dir
            // 有 fragment 的，去掉后就是有效下载路径
            if var urlComp = URLComponents(string: httpUrl) {
                urlComp.fragment = nil
                self.url = urlComp.url!.absoluteString
            }
        } else {
            self.url = httpUrl
        }
    }

    private func add() {
        if !self.checkParams() {
            return
        }
        Task {
            do {
                let hls = try await HLS(url: self.url)
                let task = Aria2Task(hls: hls, saveDir: self.saveDir)
                let ok = try await Aria2.shared.download(task: task)
                self.msg = "创建下载任务 [\(self.saveDir)]：\(ok ? "成功" : "失败")"
                self.saveDir = ""
            } catch {
                self.msg = "解析: \(url) 失败"
            }
        }
    }

    private func checkParams() -> Bool {
        self.saveDir = self.saveDir.trimmingCharacters(
            in: CharacterSet.whitespaces)
        self.url = self.url.trimmingCharacters(in: CharacterSet.whitespaces)
        // 检测空白
        if self.url.isEmpty {
            self.msg = "下载地址为空"
            return false
        }
        if !self.url.contains(".m3u8") {
            self.msg = "下载链接只支持 m3u8 类型"
            return false
        }
        if self.saveDir.isEmpty {
            self.msg = "保存目录为空"
            return false
        }
        return true
    }
}

#Preview {
    ContentView()
}
